package com.kum.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline;
import com.github.monkeywie.proxyee.intercept.common.FullResponseIntercept;
import com.kum.domain.constant.ScriptConstant;
import com.kum.domain.entity.SysScript;
import com.kum.service.UserCacheService;
import com.kum.utils.HttpUtils;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Package com.kum.handler
 * @auhter 枯木Kum
 * @date 2021/6/15-6:19 PM
 * <p>...</p>
 */

@Log4j2
@Component
public class MyFullResponseIntercept extends FullResponseIntercept {

    @Autowired
    private UserCacheService userCacheService;

    @Override
    public boolean match(HttpRequest httpRequest, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) {
        String ip = httpRequest.headers().get("ip");
        if (!HttpUtils.isHtml(httpRequest, httpResponse)) {
            return false;
        }
        Map<String, Object> userScriptMatchs = userCacheService.getUserScriptMatchs(ip);
        //设置需要响应的脚本id集合
        List<String> scripts = new ArrayList<>();
        for (String match : userScriptMatchs.keySet()) {
            String currentUrl = "http://" + pipeline.getHttpRequest().headers().get("Host") + pipeline.getHttpRequest().uri();
            if (HttpUtils.ruleMatch(match, currentUrl)) {
                JSONObject object = JSON.parseObject((String) userScriptMatchs.get(match));
                if(object.getString("status").equals(ScriptConstant.enable)){
                    scripts.add(object.getString("scriptId"));

                }
            }
        }

        httpRequest.headers().add("scripts", JSON.toJSONString(scripts));
        log.info("ip: {},进入代理服务器, 匹配脚本数量: {}",ip,scripts.size());
        return scripts.size() > 0;


    }


    @Override
    public void handleResponse(HttpRequest httpRequest, FullHttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) {

        String content = httpResponse.content().toString(Charset.defaultCharset());
        httpResponse.content().clear();
        httpResponse.content().writeBytes(content.getBytes());

        for (Object scripts : JSON.parseArray(httpRequest.headers().get("scripts"))) {
            SysScript script = userCacheService.getScript(String.valueOf(scripts));
            List<String> requires = script.getRequire();
            log.info("拥有依赖项: {} 个",requires.size());
            for (String require : requires) {
                httpResponse.content().writeBytes(("<script src=\"" + require + "\"></script>").getBytes());
            }

            httpResponse.content().writeBytes(("<script type=\"text/javascript\">" + script.getScriptText() + "</script>").getBytes());
        }


    }
}
